package com.example.adminjiemian;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends AppCompatActivity {
    private EditText etLoginUsername;
    private EditText etLoginPassword;
    private Button btnLogin;
    private Button btnRegisiter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        etLoginUsername = (EditText) findViewById(R.id.et_login_username);
        etLoginPassword = (EditText) findViewById(R.id.et_login_password);
        btnLogin = (Button) findViewById(R.id.btn_login);
        btnRegisiter = (Button) findViewById(R.id.btn_regisiter);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==1){
                if (data!=null){
                    etLoginUsername.setText(data.getStringExtra("username"));
                    etLoginPassword.setText(data.getStringExtra("password"));
                }
            }
        }
        else {
            etLoginUsername.setText(data.getStringExtra(""));
            etLoginPassword.setText(data.getStringExtra(""));
        }
    }

    public void doLogin(View view) {
        String prefName="com.example.adminjiemian";
        SharedPreferences sharedPreferences=getSharedPreferences(prefName,MODE_PRIVATE);

        String s = etLoginUsername.getText().toString();
        String username = sharedPreferences.getString("username"+s, null);

        if(username==null){
            Toast.makeText(this,"用户不存在请注册",Toast.LENGTH_SHORT).show();
        }else {
            String passwordSaved = sharedPreferences.getString("password"+s, null);
            String password = etLoginPassword.getText().toString();
            if(password.equals(passwordSaved)){

                Intent intent = new Intent(this, MainActivity.class);

                intent.putExtra("username",s);
                intent.putExtra("password",password);
                intent.putExtra("gender",sharedPreferences.getBoolean("gender"+s,false));
                intent.putExtra("age",sharedPreferences.getInt("age"+s,0));
                startActivity(intent);
            }else {
                Toast.makeText(this,"用户名或密码错误",Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void doReg(View view) {
        Intent intent=new Intent(this,Regisit.class);
        startActivityForResult(intent,1);
    }
}
